package com.anbinh.doctor.fragment.account;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.PermissionDetailtAdapter;
import com.anbinh.doctor.model.NewAvatar;
import com.anbinh.doctor.model.ResponseAssistants.Data.Assistants;
import com.anbinh.doctor.model.ResponsePermission;
import com.anbinh.doctor.model.ResponsePermission.Item;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class FragmentAssistantDetailt extends Fragment {
	private static FragmentAssistantDetailt fragment = null;
	private View mView;
	private CircleProgressBar loadding;
	public final static int REQ_EDIT_AVATAR = 122;
	public final static int REQ_ATTACH_FILE = 2;
	private ImageView avatar;
	private UserLogin userLogin;
	private TextView lblName;
	private PermissionDetailtAdapter adapter;
	private List<Item> mListSp;
	private ListView mListview;
	protected Item currentPermission;

	public static FragmentAssistantDetailt newInstance() {
		if (fragment == null) {
			fragment = new FragmentAssistantDetailt();
		}
		return fragment;
	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_message, null);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);

		mListview = (ListView) mView.findViewById(R.id.listView1);
		View header = getActivity().getLayoutInflater().inflate(
				R.layout.header_assistiant, null);
		mListview.addHeaderView(header);
		loadding = (CircleProgressBar) header.findViewById(R.id.loadding);
		Assistants assistants = FragmentAssistantList.newInstance()
				.getCurrentAssistants();
		lblName = (TextView) header.findViewById(R.id.lblName);
		lblName.setText(assistants.getFullname());
		TextView lblBrithday = (TextView) header.findViewById(R.id.lblBrithday);
		lblBrithday.setText(assistants.getPhone());

		avatar = (ImageView) header.findViewById(R.id.avatar);
		avatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				pickFile(getActivity(), REQ_EDIT_AVATAR);
			}
		});
		ImageLoader imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()
				.getApplicationContext()));

		Bitmap bmp = imageLoader.loadImageSync(assistants.getAvatar());
		if (bmp == null) {

			imageLoader.displayImage(assistants.getAvatar(), avatar,
					Utils.getOptions(getActivity()),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
						}
					});
		} else {
			avatar.setImageBitmap(bmp);
		}

		onLoadData();
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0)
					return;
				currentPermission = mListSp.get(position - 1);
				onClickItem(position - 1);
			}
		});
	}

	public Item getCurrentPermission() {
		return currentPermission;
	}

	private void onLoadData() {
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		UserLogin userLogin = Utils.getAccountModel(getActivity(),
				Utils.KEY_USER);
		String token = userLogin.getData().getToken();
		ServerController.getInstance(getActivity()).reuquestListPermission(
				token, new OnRequest<ResponsePermission>() {

					@Override
					public void onSuccess(ResponsePermission data) {
						if (getActivity() == null)
							return;

						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						if (data.getResponsecode() >= 0) {
							mListSp = data.getData();
							adapter = new PermissionDetailtAdapter(
									getActivity(), R.layout.item_account,
									mListSp, 0);
							mListview.setAdapter(adapter);

						}
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.GONE);
					}
				});
	}

	public void updateInfo(Intent data) {
		final UserLogin user = Utils.getAccountModel(getActivity(),
				Utils.KEY_USER);

		String token = user.getData().getToken();
		Uri selectedImage = data.getData();
		avatar.setImageURI(selectedImage);
		File file = new File(Utils.getRealPathFromURI(getActivity(),
				selectedImage));
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestUploadAvatar(token,
				file, new OnRequest<NewAvatar>() {

					@Override
					public void onSuccess(NewAvatar data) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						if (data.getResponsecode() >= 0) {
							userLogin.getData().getUserInfo()
									.setAvatar(data.getData().getNewAvatar());
							Utils.updateData(getActivity(), Utils.KEY_USER,
									userLogin);
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						Utils.showMessage(getActivity(), message);
					}
				});
	}

	public void pickFile(Activity activity, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_PICK);

		// TODO Auto-generated method stub
		// call android default gallery
		intent.setType("image/*");
		// ******** code for crop image
		activity.startActivityForResult(intent, requestCode);

	}

	public void onClickItem(int position) {
		Bundle bundle = new Bundle();
		bundle.putInt(Utils.KEY, Utils.SET_PERMISSION);
		bundle.putBoolean(Utils.CUSTOMBAR, true);
		bundle.putString(Utils.TITLE, mListSp.get(position).getName());
		Utils.getNewIntent(getActivity(), bundle);
	}

}
